﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading;
using BUS;
using DTO;

namespace GUI
{
    public partial class MonAn : Form
    {
        public MonAn()
        {
            InitializeComponent();
        }

        private void MonAn_Activated(object sender, EventArgs e)
        {
            KhoiTao();
        }

        DataTable datatable = new DataTable();
        //private void MonAn_Load(object sender, EventArgs e)
        //{
        //    int somon = 0;
            
            
        //    datatable = MonAnBUS.SelectMonAnAll(ref somon);

        //    dataGridView_danhSachMon.DataSource = datatable;
        //    txt_tongMon.Text = somon.ToString();                
        //}
        private int NapDuLieu()
        {
            int soMon = 0;
            datatable = MonAnBUS.SelectMonAnAll(ref soMon);

            if (soMon != 0)
            {
                //dataGridView_danhSachMon.DataSource = datatable;

                txt_tongMon.Text = soMon.ToString();
                //test nhap
                dataGridView_danhSachMon.Rows.Clear();
                for (int i = 0; i < datatable.Rows.Count; i++)
                {
                    DataRow row = datatable.Rows[i];
                    dataGridView_danhSachMon.Rows.Add(row[0], row[1], row[2], row[3].ToString());
                }
            }
            return soMon;
        }

        private void KhoiTao()
        {           
            //show combobox LoaiMonAn
            List<LoaiMonDTO> lscbmaDTO = new List<LoaiMonDTO>();
            lscbmaDTO = LoaiMonAnBUS.SelectLoaiMonAnAll();
            
            cmbLoaiMon.DisplayMember = "TenLoai";
            cmbLoaiMon.ValueMember = "Ma_Loai";
            cmbLoaiMon.DataSource = lscbmaDTO;
            cmbLoaiMon.SelectedIndex = 0;

            List<LoaiMonDTO> lscbmaDTO2 = LoaiMonAnBUS.SelectLoaiMonAnAll();
            clLoai.DisplayMember = "TenLoai";
            clLoai.ValueMember = "Ma_Loai";
            clLoai.DataSource = lscbmaDTO2;
            clLoai.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;

            int soMon = NapDuLieu();

            if (soMon != 0)
            {
                btn_lamMoi.Enabled = true;
            }
            else
            {
                btn_lamMoi.Enabled = false;
            }
        }
        private SqlConnection conn;
        private SqlTransaction trans;
        private DataSet ds;
        private SqlDataAdapter da;
        bool IsTran { get; set; }

        private string sql;
        MonAnDTO monAnDTO = new MonAnDTO();
        private void btn_tao_Click(object sender, EventArgs e)
        {
            //Lay thong tin MonAn
            
            monAnDTO.Ma_Mon = txtMaMon.Text;
            monAnDTO.TenMon = txtTenMon.Text;
            monAnDTO.Loai = cmbLoaiMon.SelectedValue.ToString();
            float temp = 0;
            float.TryParse(txtGiaTien.Text, out temp);
            monAnDTO.GiaTien = temp;
            //MessageBox.Show(monAnDTO.Ma_Mon+" "+monAnDTO.TenMon+" "+monAnDTO.Loai+" "+monAnDTO.GiaTien.ToString());
            //Khoi tao store proc
            conn = MonAnBUS.CreateConnection();

            IsolationLevel iso = IsolationLevel.Serializable;
            conn.Open();

            trans = conn.BeginTransaction(iso);
            //MessageBox.Show("Begin transaction...");
            
            //start tran
            tsslWaitting.Visible = true;

            IsTran = true;

            //create query
            LoadQuery();
            

            DataTable datatable ;
            datatable= ExcuteSql(sql);
            Thread.Sleep(5000);

            int count=0;
            int flag = 0;
            if (datatable != null)
            {
                count = datatable.Rows.Count;
            }
            
            if (count == 0)
            {
                String sqlInsert = "Insert into MonAn(Ma_Mon,TenMon,Loai, GiaTien) Values('";
                sqlInsert += monAnDTO.Ma_Mon + "',N'" + monAnDTO.TenMon + "','" + monAnDTO.Loai + "'," + monAnDTO.GiaTien + ");";
                //MessageBox.Show(sql);
                flag = ExcuteNonSql(sqlInsert);
            }
            else
            {
                //nhap
                MessageBox.Show("Mon an da ton tai");
                
            }

            tsslWaitting.Visible = false;
 
            //commit tran
            //MessageBox.Show("Commit Transaction.");
            trans.Commit();
            conn.Close();
            MessageBox.Show("Thêm thành công.");
            

            IsTran = false;

            //reload datagripview
            NapDuLieu();
        }

        private void LoadQuery()
        {
            if (chbFixTran.Checked == false)
            {
                sql = "select * from MonAn where TenMon=N'" + monAnDTO.TenMon + "'";
            }
            else
            {
                sql = "select * from MonAn with (Xlock) where TenMon=N'" + monAnDTO.TenMon + "'";
            }
        }

        private int ExcuteNonSql(string sql)
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                var cmd = new SqlCommand(sql, conn, trans);
                return cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                if (ex.Number == -2)
                    throw new ApplicationException("Timeout expired");
                throw new ApplicationException(ex.Message);
            }
            finally
            {
                if (IsTran == false)
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                }
            }
        }

        private DataTable ExcuteSql(string sql)
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                var cmd = new SqlCommand(sql, conn, trans);
                //cmd.CommandTimeout = 5000;

                da = new SqlDataAdapter(cmd);
                ds = new DataSet();

                da.Fill(ds);

                if (ds.Tables.Count > 0 && ds.Tables[0] != null)
                {
                    return ds.Tables[0];
                }
            }
            catch (SqlException ex)
            {
                if (ex.Number == -2)
                    throw new ApplicationException("Timeout expired");
                throw new ApplicationException(ex.Message);
            }
            finally
            {
                if (IsTran == false)
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                }
            }
            return null;
        }

        private void btn_lamMoi_Click(object sender, EventArgs e)
        {
            cmbLoaiMon.SelectedIndex = 0;
            txtMaMon.Text = null;
            txtTenMon.Text=null;
            txtGiaTien.Text = null;
            txt_tongMon.Text = NapDuLieu().ToString();

        }

        private void btn_thoat_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
        
    }
}
